var businessLabelApp = new Vue({
    el: '#businessLabelApp',
    data: {
        // 业务标签配置
        businessLabelSettingFilterParameters:{
            current: 1,
            pageSize: 10,
            searchKey: ''
        },
        // 业务标签配置List
        businessLabelSettingList: {
            data: [],
            current:0,
            pages: 0,
            total: 0,
            size: 0
        },
        // 业务标签List
        businessLabelList: [],
        // 已选中的业务标签
        selectedBusinessLabelList: [],
        // 显示选择部门控件
        showDepartmentSelector: false,
        // 组织架构
        departments: [],
        // 选中部门名称
        selectedDepartmentName: "",
        // 选中部门ID
        selectedDepartmentId: -1,
        // 组织架构筛选参数
        departmentsFilterParameters: {
            searchKey: "",
            companyId: -1,
        },
        // 负责人
        inChargePersonList: [],
        // 选中负责人
        selectedInChargePerson:{},
        showAddBusinessLabelSettingModal: false,
        // 显示选择部门错误提示
        showSelectDepartmentError: false,
        // 显示选择主要负责人控件
        showInChargePersonSelector: false,
        // 显示添加业务标签模态框
        showAddBusinessLabelModal: false,
        // 组织架构渲染块
        departmentsRender: "",
        selectInChargePersonSearchKey: "",
        // 选中的业务标签配置
        selectedBusinessLabelSettingId: -1,
    },
    mounted:  function(){
        this.initData()
    },
    directives: {
        strip: {
            twoWay: true,
            bind:function (el,binding, vnode) {
                el.addEventListener('keyup',function () {
                    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？+-]")
                    var rs = "";
                    for (var i = 0; i < el.value.length; i++) {
                        rs = rs + el.value.substr(i, 1).replace(pattern, '');
                    }
                    el.value = rs
                })
            },
            update:function (el,binding,vnode) {
                if(el.value !== ''){
                    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？+-]")
                    var rs = "";
                    for (var i = 0; i < el.value.length; i++) {
                        rs = rs + el.value.substr(i, 1).replace(pattern, '');
                    }
                    el.value = rs
                }
            }
        }
    },
    watch: {
        selectInChargePersonSearchKey: function() {
            this.getInChargePersonList()
        }
    },
    methods: {
        // 初始化页面数据
        initData: function() {
            this.getBusinessLabelSettingList()
            VUE_UTIL.delegate("click", "unFoldBtn", function(event){
                debugger
                var btn = event.target;
                if(btn.innerHTML == "+") {
                    btn.innerHTML = "-";
                } else {
                    btn.innerHTML = "+";
                }
                var subTreeNode = VUE_UTIL.getChild(btn.parentNode.nextElementSibling, "treeNode");
                VUE_UTIL.toggleElement(subTreeNode);
                VUE_UTIL.hideElement(VUE_UTIL.getChildren())
            })
            VUE_UTIL.delegate("click", "department", function(event){
                var target = event.target;
                businessLabelApp.selectedDepartmentName = target.getAttribute("data-departName");
                businessLabelApp.selectedDepartmentId = target.getAttribute("data-id");
                document.getElementsByClassName("selectedDepartment")[0].value = target.getAttribute("data-departName")
                document.getElementsByClassName("department-container")[0].innerHTML = "";
                businessLabelApp.showDepartmentSelector = false;
            })
        },
        // 查询
        search: function(event) {
            this.businessLabelSettingFilterParameters.searchKey = this.businessLabelSettingFilterParameters.searchKey.trim()
            this.getBusinessLabelSettingList()
        },
        // 业务标签配置列表
        getBusinessLabelSettingList: function() {
            var _self = this
            var postData = {
                current: this.businessLabelSettingFilterParameters.current,
                pageSize: this.businessLabelSettingFilterParameters.pageSize,
                searchKey: this.businessLabelSettingFilterParameters.searchKey
            }
            VUE_UTIL.getAxiosInstance().post("/basedata/erpBusinessLabel/findPage",VUE_UTIL.buildPostFormData(postData))
                .then(function(response){
                    _self.businessLabelSettingList = {
                        data: response.data.data.records,
                        current: response.data.data.current,
                        pages: response.data.data.pages,
                        total: response.data.data.total,
                        size: response.data.data.size
                    };
                    _self.initPaging()
                })
        },
        // 初始化分页显示
        initPaging: function() {
            var _self = this;
            layui.use(['laypage', 'layer'], function () {
                var laypage = layui.laypage;
                laypage({
                    cont: 'turn-page',
                    curr: _self.businessLabelSettingList.current || 1,
                    pages: _self.businessLabelSettingList.pages,
                    skin: '#457fe6',
                    skip: true,
                    jump: function (obj, first) {
                        if (!first) {
                            _self.businessLabelSettingFilterParameters.current = obj.curr
                            _self.getBusinessLabelSettingList()
                        }
                    }
                });
            });
        },
        // 删除业务标签配置
        delLabelCon: function(labelCon) {
            var _self = this
            layer.alert('是否确认删除该业务标签配置？', {
                    title: '提示信息',
                    btn: ['取消', '确认'],
                    btn1: function (index) {
                        layer.close(index)
                    },
                    btn2: function () {
                        var postData = {
                            id: labelCon.id
                        };
                        VUE_UTIL.getAxiosInstance().post("/basedata/erpBusinessLabel/delete",VUE_UTIL.buildPostFormData(postData))
                        .then(function(response){
                            layer.msg(response.data.data, {time: 1000});
                            _self.businessLabelSettingFilterParameters.current = 1;
                            _self.getBusinessLabelSettingList()
                        })
                    }
                }
            );
        },
        // 获取所有标签
        getBusinessLabelList: function() {
            var _self = this
            VUE_UTIL.getAxiosInstance().post("/basedata/erpIntentionLabel/findAll",{})
                .then(function(response){
                    _self.businessLabelList = response.data.data
                })
        },
        // 编辑业务标签配置
        editLabelCon: function(labelCon) {
            var _self = this
            this.resetAddBusinessLabelSettingModal();
            this.selectedBusinessLabelSettingId = labelCon.id;
            this.selectedDepartmentName = labelCon.responsibleDepartName;
            this.selectedDepartmentId = labelCon.responsibleDepart;
            this.selectedInChargePerson = {
                employeeId: labelCon.responsiblePerson,
            };
            this.getDepartments();
            this.showDepartmentSelector = false
            var labelIdsArr = [];
            if(labelCon.labelIds) {
                labelIdsArr = labelCon.labelIds.split(",");
            }
            VUE_UTIL.getAxiosInstance().post("/basedata/erpIntentionLabel/findAll",{})
                .then(function(response){
                    _self.businessLabelList = response.data.data
                    for(var i = 0; i < _self.businessLabelList.length; i ++) {
                        _self.businessLabelList[i].seleted = false
                        for(var j = 0; j < labelIdsArr.length; j++) {
                            if(_self.businessLabelList[i].id == labelIdsArr[j]) {
                                _self.selectedBusinessLabelList.push(_self.businessLabelList[i]);
                                _self.businessLabelList[i].seleted = true
                            }
                        }
                    }
                    document.getElementsByClassName("selectedDepartment")[0].value = labelCon.responsibleDepartName;
                    _self.selectInChargePersonSearchKey = labelCon.responsiblePersonName;
                    _self.showAddBusinessLabelSettingModal = true;
                })
        },
        // 获取组织架构树形
        getDepartments: function() {
            var _self = this
            var requestUrl = VUE_UTIL.buildRequestUrl("/basedata/department/queryAllListJSON", {
                searchKey: this.departmentsFilterParameters.searchKey
            })
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    // 组织架构json
                    _self.departments = _self.transFormatToTree(response.data.data);
                    var departmentTreeRender = document.getElementsByClassName("department-container")[0];
                    departmentTreeRender.innerHTML = _self.buildDepartmentTree(_self.departments, true);
                })
        },
        // 渲染组织架构树形
        buildDepartmentTree: function(departmentsJson, flag) {
            var _html = "";
            if (flag) {
                _html += "<ul class='treeNode'>";
            } else {
                _html += "<ul class='treeNode hidden'>";
            }
            for (var i = 0; i < departmentsJson.length; i ++) {
                if(departmentsJson[i].children && departmentsJson[i].children.length > 0) {
                    _html += "<li data-id='" + departmentsJson[i].id +"' data-departName='" + departmentsJson[i].name +"' class='hasChildren department'><span class='unFoldBtn'>+</span>" + departmentsJson[i].name + "</li>";
                    _html += "<li>";
                    _html += this.buildDepartmentTree(departmentsJson[i].children, false)
                    _html += "</li>";
                } else {
                    _html +=    "<li data-id='" + departmentsJson[i].id +"' class='department' data-departName='" + departmentsJson[i].name + "' ><span></span>" + departmentsJson[i].name + "</li>";
                }
            }
            _html += "</ul>";
            return _html;
        },
        // 显示选择部门控件
        showSelectDepartment: function() {
            this.showSelectDepartmentError = false
            this.showDepartmentSelector = true;
            this.getDepartments();
        },
        // 选择部门检索
        searchForDepartment: function() {
            this.selectedDepartmentId = -1
            var input = event.target.value
            this.departmentsFilterParameters.searchKey = input
            this.getDepartments()
        },
        // 隐藏选择部门控件
        hideSelectDepartment: function() {
            this.showDepartmentSelector = false;
            this.getDepartments();
        },
        // 获取主要负责人
        getInChargePersonList: function() {
            var _self = this
           if(this.selectedDepartmentId == -1) {
               this.showSelectDepartmentError = true
               return false;
           } else {
                var departmentId = this.selectedDepartmentId
               var searchKey = document.getElementsByClassName("inChargePersonSearchKey")[0].value;
               var postData = {
                   departmentId: departmentId,
                   searchKey: searchKey
               };
               VUE_UTIL.getAxiosInstance().post("/basedata/employee/queryEmployeeJson",VUE_UTIL.buildPostFormData(postData))
                   .then(function(response){
                       _self.inChargePersonList = response.data.data;
                   })
           }
        },
        // 显示选择主要负责人控件
        showSelectInChargePerson: function() {
            this.showDepartmentSelector = false;
            this.showInChargePersonSelector = true;
            this.getInChargePersonList();
        },
        // 添加业务标签
        addBusinessLabelSetting: function(){
            this.resetAddBusinessLabelSettingModal();
            this.showAddBusinessLabelSettingModal = true;
            this.getBusinessLabelList();
        },

        // 显示标签操作按钮
        showLabelOperators: function(event) {
            var labelOperator = document.getElementsByClassName("label-operator");
            var element = event.target.nextElementSibling;
            if (VUE_UTIL.hasClass(element, "hidden")) {
                VUE_UTIL.hideElement(labelOperator)
                VUE_UTIL.showElement(element)
            } else {
                VUE_UTIL.hideElement(labelOperator)
                VUE_UTIL.hideElement(element)
            }
        },
        // 删除标签
        deleteLabel: function(label) {
            var _self = this
            var editor = document.getElementsByClassName("edit")
            for(var i = 0; i < editor.length; i++) {
                VUE_UTIL.showElement(editor[i].previousElementSibling)
            }
            VUE_UTIL.hideElement(editor)
            var labelOperator = document.getElementsByClassName("label-operator");
            for (var i = 0; i < labelOperator.length; i ++) {
                if(labelOperator[i].style.display == "block") {
                    labelOperator[i].style.display = "none"
                }
            }
            layer.alert('是否确认删除该标签？', {
                    title: '提示信息',
                    btn: ['取消', '确认'],
                    btn1: function (index) {
                        layer.close(index)
                        var labelOperator = document.getElementsByClassName("label-operator");
                        VUE_UTIL.hideElement(labelOperator)
                    },
                    btn2: function () {
                        var labelOperator = document.getElementsByClassName("label-operator");
                        VUE_UTIL.hideElement(labelOperator)
                        for(var i = 0; i < _self.businessLabelList.length; i++) {
                            if(_self.businessLabelList[i].id == label.id) {
                                _self.businessLabelList.splice(i, 1)
                            }
                        }
                        var postData = {
                            id: label.id
                        };
                        VUE_UTIL.getAxiosInstance().post("/basedata/erpIntentionLabel/delete",VUE_UTIL.buildPostFormData(postData))
                            .then(function(response){
                                layer.msg(response.data.msg, {time: 1000});
                                _self.getBusinessLabelList();
                            })
                    }
                }
            );
        },
        // 编辑标签
        editLabel: function(event) {
            var element = event.target;
            var editor = element.parentElement.parentElement.previousElementSibling;
            VUE_UTIL.hideElement(editor.previousElementSibling)
            VUE_UTIL.hideElement(element.parentElement)
            if(VUE_UTIL.hasClass(editor, "hidden")) {
                VUE_UTIL.showElement(editor)
            } else {
                VUE_UTIL.hideElement(editor)
                VUE_UTIL.showElement(editor.previousElementSibling)
            }
        },
        /**
         * 取消标签修改
         * @param event
         */
        cancelEdit: function(event) {
            var element = event.target;
            var editor = element.parentElement;
            this.getBusinessLabelList();
            VUE_UTIL.hideElement(editor);
            VUE_UTIL.showElement(editor.previousElementSibling);
        },
        /**
         *  保存标签修改
         * @param label
         */
        saveEdit: function(label) {
            var _self = this;
            if(label.labelName.trim() == ""){
                layer.msg('标签名不能为空', {time: 1000});
                _self.getBusinessLabelList();
                return false
            }
            var postData = {
                id: label.id,
                labelName: label.labelName
            };
            VUE_UTIL.getAxiosInstance().post("/basedata/erpIntentionLabel/update",VUE_UTIL.buildPostFormData(postData))
                .then(function(response){
                    layer.msg(response.data.msg, {time: 1000});
                    _self.getBusinessLabelList();
                    VUE_UTIL.hideElement(document.getElementsByClassName("edit"))
                    VUE_UTIL.showElement(document.getElementsByClassName("labelName"))
                })
        },
        /**
         * 添加标签到已选标签
         */
        addToSelectedLabels: function() {
            this.selectedBusinessLabelList = [];
            var temp = []
            var labelRows = document.getElementsByClassName("label-row");
            for(var i = 0; i < labelRows.length; i++) {
                var checkbox = VUE_UTIL.getChildren(labelRows[i], "isSelected")[0];
                if(checkbox && checkbox.checked) {
                    temp.push({
                        id: checkbox.previousElementSibling.previousElementSibling.value,
                        labelName: checkbox.previousElementSibling.value,
                    })
                }
            }
            this.selectedBusinessLabelList = temp;
        },
        /**
         * 移除已选标签
         */
        removeFromSelected: function(selectedBusinessLabel) {
            var selectedBusinessLabelId = selectedBusinessLabel.id;
            for(var i = 0; i < this.selectedBusinessLabelList.length; i ++) {
                if(this.selectedBusinessLabelList[i].id == selectedBusinessLabelId) {
                    this.selectedBusinessLabelList.splice(i, 1);
                }
            }
        },
        /**
         * 保存添加业务标签
         */
        saveBusinessLabel: function(event) {
            var _self = this;
            var textArea = document.getElementsByClassName("businessLabelTextArea")[0];
            var labelStr = textArea.value;
            var labelArr = labelStr.replace(/\n/g,",").split(",")
            for(var i = 0; i<labelArr.length; i++) {
                if(labelArr[i].trim() == '') {
                    labelArr.splice(i)
                }
            }
            if(labelArr.length > 0) {
                for(var i=0; i<labelArr.length; i++) {
                    if(labelArr[i].length > 50) {
                        layer.msg("标签名称长度不能超过50", {time: 1000});
                        textArea.value=""
                        return false
                    }
                }
            } else {
                layer.msg('请输入至少一个业务标签，不能为空字符串', {time: 1000})
                textArea.value=""
                return false
            }
            axios.post('/basedata/erpIntentionLabel/addBatchLabel', {
                labelList: VUE_UTIL.removeEmptyElement(labelArr),
            })
            .then(function (response) {
                layer.msg(response.data.msg, {time: 1000});
                _self.showAddBusinessLabelModal = false;
                textArea.value="";
                _self.getBusinessLabelList();
            })
            .catch(function (error) {
                layer.msg(response.data.msg, {time: 1000});
                _self.showAddBusinessLabelModal = false;
            });
        },
        /**
         * 将数据转为树形结构
         * @param data
         */
        transFormatToTree: function(data) {
            var obj = {};
            var objArr = [];
            for (var i = 0; i < data.length; i++) {
                if(!data[i].id){
                    return false
                }
                var key = data[i]['id'];
                obj[key] = {
                    'Name': data[i]['name'].toString(),
                    'ID': data[i]['id'].toString(),
                    'ParentID': data[i]['parentId'].toString()
                }
                objArr.push({
                    name: data[i]['name'].toString(),
                    id: data[i]['id'].toString(),
                    parentId: data[i]['parentId'].toString()
                })
            }
            var resultObj = convert(obj, 0) //根id为0
            function convert(source, rootpid) {
                var tmp = {}, parent, n;
                for (n in source) {
                    var item = source[n];
                    if (item.ID == item.ParentID) {
                        parent = item.ID;
                    }
                    if (!tmp[item.ID]) {
                        tmp[item.ID] = {};
                    }
                    tmp[item.ID].name = item.Name;
                    tmp[item.ID].id = item.ID;
                    if (!("children" in tmp[item.ID])) tmp[item.ID].children = [];

                    if (item.ID!= item.ParentID) {
                        if (tmp[item.ParentID]) {
                            tmp[item.ParentID].children.push(tmp[item.ID]);
                        }
                        else {
                            tmp[item.ParentID] = {
                                children: [tmp[item.ID]]
                            };
                        }
                    }
                }
                return tmp[rootpid];
            }
            if(resultObj && resultObj.children) {
                return resultObj.children
            } else {
                return objArr
            }
        },
        /**
         * 选择主要负责人
         * @param inChargePerson
         */
        selectInChargePerson: function(inChargePerson) {
            this.selectInChargePersonSearchKey = inChargePerson.employeeName;
            this.selectedInChargePerson = inChargePerson;
            this.showInChargePersonSelector = false
            debugger
        },
        /**
         * 保存业务标签配置
         */
        saveBusinessLabelSetting: function() {
            var _self = this;
            var selectedLabelIdList = [];
            for(var i = 0; i < this.selectedBusinessLabelList.length; i ++) {
                selectedLabelIdList.push(this.selectedBusinessLabelList[i].id);
            }
            debugger
            // 字段必填验证
            if(this.selectedDepartmentId == -1) {
                layer.msg('请选择负责部门', {time: 1000});
                return false
            } else if(VUE_UTIL.isEmpty(this.selectedInChargePerson)) {
                layer.msg('请选择主要负责人', {time: 1000});
                return false
            } else if(selectedLabelIdList.length == 0){
                layer.msg('请至少选择一个标签', {time: 1000})
                return false
            }
            var postData;
            if(this.selectedBusinessLabelSettingId != -1) {
                postData = {
                    id: this.selectedBusinessLabelSettingId,
                    labelIdList: selectedLabelIdList,
                    responsibleDepart: this.selectedDepartmentId,
                    responsiblePerson: this.selectedInChargePerson.employeeId,
                };
            } else {
                postData = {
                    labelIdList: selectedLabelIdList,
                    responsibleDepart: this.selectedDepartmentId,
                    responsiblePerson: this.selectedInChargePerson.employeeId,
                };
            }

            axios.post('/basedata/erpBusinessLabel/addOrUpdate',postData)
                .then(function (response) {
                    layer.msg(response.data.msg, {time: 1000});
                    _self.showAddBusinessLabelSettingModal = false;
                    _self.getBusinessLabelSettingList();
                })
                .catch(function (error) {
                    layer.msg(response.data.msg, {time: 1000});
                    _self.showAddBusinessLabelSettingModal = false;
                });
        },
        // 重置添加业务标签配置模态框里的内容
        resetAddBusinessLabelSettingModal: function() {
            this.selectedInChargePerson = {};
            this.selectedDepartmentId = -1;
            this.selectedDepartmentName = "";
            this.selectedBusinessLabelList = [];
            this.selectedBusinessLabelSettingId = -1;
            document.getElementsByClassName("selectedDepartment")[0].value=""
            this.selectInChargePersonSearchKey = ""
            this.showDepartmentSelector = false
            this.showInChargePersonSelector = false
            this.showSelectDepartmentError = false
            this.showAddBusinessLabelModal = false
            this.getDepartments()
            document.getElementsByClassName("businessLabelTextArea")[0].value=""
        },
        // 移除已选中的部门ID
        clearDepartmentId: function() {
            this.selectedDepartmentId = -1
        },
        // 移除已选中主要负责人
        clearInChargePerson: function() {
            this.selectedInChargePerson = {}
        },
        cancelAddBusinessLabel: function() {
            this.showAddBusinessLabelModal = false;
            var textArea = document.getElementsByClassName("businessLabelTextArea")[0];
            textArea.value="";
        },

    },
})

function stripScript(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}